package cn.imvc.app.models;

import java.util.List;
import java.util.Set;

import javax.swing.text.StyledEditorKit.BoldAction;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Menu;
import cn.imvc.app.entities.Role;
import cn.imvc.app.repositories.MenuRepository;
import cn.imvc.core.DialogBean;
import cn.imvc.core.HttpContext;

@Service
public class MenuModelImpl implements MenuModel {
	@Autowired
	MenuRepository menuRepository;

	public String getMenuTree() {
		String rootUrl = HttpContext.getContext().getAttribute("rootUrl")
				.toString();
		List<Menu> menus = menuRepository.findByParentIsNull(new Sort(Direction.DESC,"order"));
		StringBuffer tree = new StringBuffer();
		for (Menu menu : menus) {
			tree.append("<li class='treeli' data_id='" + menu.getId()
					+ "'><a href='" + rootUrl + "/system/menu/" + menu.getId()
					+ "/edit' target='ajax' rel='menuBox'>" + menu.getName()
					+ "</a>");
			tree.append(getChildMenu(menu, rootUrl));
			tree.append("</li>");

		}
		return tree.toString();
	}

	private String getChildMenu(Menu menu, String rootUrl) {
		StringBuffer childNode = new StringBuffer();

		if (menu.getMenu().size() > 0) {
			childNode.append("<ul>");
			for (Object object : menu.getMenu()) {
				Menu childMenu = (Menu) object;
				childNode.append("<li class='treeli' data_id='"
						+ childMenu.getId() + "'><a href='" + rootUrl
						+ "/system/menu/" + childMenu.getId()
						+ "/edit' target='ajax' rel='menuBox'>"
						+ childMenu.getName() + "</a>");
				childNode.append(getChildMenu(childMenu, rootUrl));
				childNode.append("</li>");
			}
			childNode.append("</ul>");
		}

		return childNode.toString();
	}

	public Menu get(int id) {
		Menu menu = null;
		if (id != 0) {
			menu = menuRepository.findOne(id);
		}
		return menu;
	}

	public Menu save(int id, Menu menu) {
		menu.setParent(get(id));
		return menuRepository.saveAndFlush(menu);
	}

	public Menu update(int id, Menu menu) {
		Menu loadMenu = get(id);
		BeanUtils.copyProperties(menu, loadMenu,
				new String[] { "id", "parent" });
		return menuRepository.saveAndFlush(loadMenu);
	}

	public DialogBean delete(int id) {
		DialogBean dialogBean = new DialogBean();
		if (get(id).getMenu().size() > 0) {
			dialogBean.setStatusCode("300");
			dialogBean.setMessage("有子菜单不能删除");
		} else {
			dialogBean.setStatusCode("200");
			dialogBean.setMessage("删除成功");
			dialogBean.setDialogId("menu");
			menuRepository.delete(id);
		}

		return dialogBean;
	}

	public String getNavMenu() {
		List<Menu> menus = menuRepository.findByParentIsNullAndType("navMenu",new Sort(Direction.DESC,"order"));
		int i = 0;
		StringBuffer navMenu = new StringBuffer();
		String a_class = "";
		String menuName = "";
		String rootUrl = HttpContext.getContext().getAttribute("rootUrl")
				.toString();
		for (Menu menu : menus) {
			if (i == 0){
				a_class = "class='selected'";
			}
			menuName = menu.getName();
			if (menu.getTitle() != null && !menu.getTitle().isEmpty()){
				menuName = menu.getTitle();
			}
			navMenu.append("<li><a " + a_class + " href='" + rootUrl
					+ "/system/index/" + menu.getId() + "'><span>" + menuName
					+ "</span></a></li>");
			i++;
		}
		return navMenu.toString();
	}
	public String getDefaultMenu(Set<Role> roles) {
		String defaultMenu="";
		Sort sort=new Sort(Direction.DESC,"order");
		List<Menu> menus = menuRepository.findByParentIsNullAndType("navMenu",sort);
		if(menus.size()>0){
			defaultMenu=getMenus(menus.get(0).getId(),roles);
		}
		return defaultMenu;
	}

	
	
	public String getMenus(int id,Set<Role> roles) {
		Menu navMenu = menuRepository.findOne(id);
		@SuppressWarnings("unchecked")
		Set<Menu> childMenu = navMenu.getMenu();
		StringBuffer defaultFolder = new StringBuffer();
		String folder = new String();
		defaultFolder.append("<div class='accordionHeader'>\n");
		defaultFolder.append("<h2><span>Folder</span>" + navMenu.getName() + "</h2>\n");
		defaultFolder.append("</div>\n");
		defaultFolder.append("<div class='accordionContent'>\n");
		defaultFolder.append("<ul class='tree treeFolder'>\n");
		int i=0;
		if (childMenu.size() > 0) {
			for (Menu menu : childMenu) {
				if (menu.getType().equals("folder")) {
					folder = getAccordion(menu,roles);
				} else {
					i++;
					defaultFolder.append(accordionContentItem(menu,roles));
				}
				
			}
		}
		defaultFolder.append("</ul>\n");
		defaultFolder.append("</div>\n");
		if(i==0){
			return folder;
		}else{
			return defaultFolder.toString() + folder;
		}
		
	}
	
	public String getAccordion(Menu menu ,Set<Role> roles) {
		StringBuffer tree = new StringBuffer();
		
		StringBuffer accordion = new StringBuffer();
		accordion.append("<div class='accordionHeader'>\n");
		accordion.append("<h2><span>Folder</span>" + menu.getName() + "</h2>\n");
		accordion.append("</div>\n");
		accordion.append("<div class='accordionContent'>\n");
		accordion.append("<ul class='tree treeFolder'>\n");
		for (Object object : menu.getMenu()) {
			Menu childMenu = (Menu) object;
			accordion.append(accordionContentItem(childMenu,roles));
		}
		accordion.append("</ul>\n");
		accordion.append("</div>\n");
		
		
		boolean authority=false;
		Set<Role> menuRole=menu.getRole();
		for (Role role : roles) {
			for (Role m_role : menuRole) {
				if(m_role.getId()==role.getId())
					authority=true;
			}
		}
		if(authority){
			tree.append(accordion);
		}else if(accordion.length()>160){
			tree.append(accordion);
		}
		
		return tree.toString();
	}

	public String accordionContentItem(Menu menu,Set<Role> roles) {
		StringBuffer tree = new StringBuffer();
		String rootUrl = HttpContext.getContext().getAttribute("rootUrl")
				.toString();
		StringBuffer accordionContent = new StringBuffer();
		accordionContent.append("<li>\n");
		if (menu.getType().equals("navTab")) {
			if (menu.getUrl() != null && !menu.getUrl().isEmpty()) {
				accordionContent.append("<a href='" + rootUrl + menu.getUrl()
						+ "' target='navTab' rel='" + menu.getRel() + "' title='"
						+ menu.getTitle() + "' fresh='" + menu.getFresh()
						+ "' external='" + menu.getExternal() + "' >"
						+ menu.getName() + "</a>\n");
			} else {
				accordionContent.append("<a href='javascript:;'>"+ menu.getName() + "</a>\n");
			}
		} else if (menu.getType().equals("dialog")) {
			if (menu.getUrl() != null && !menu.getUrl().isEmpty()) {
				accordionContent.append("<a href='" + rootUrl + menu.getUrl()
						+ "' target='dialog' rel='" + menu.getRel() + "' title='"
						+ menu.getTitle() + "' minable='" + menu.getMinable()
						+ "' mixable='" + menu.getMixable() + "' resizable='"
						+ menu.getResizable() + "' drawable='" + menu.getDrawable()
						+ "' width='" + menu.getWidth() + "' height='"
						+ menu.getHeight() + "' fresh='" + menu.getFresh()
						+ "'>" + menu.getName() + "</a>\n");
			}else{
				accordionContent.append("<a href='javascript:;'>" + menu.getName() + "</a>\n");
			}
		}
		String menuTree=getchildMenuTree(menu, rootUrl,roles);
		accordionContent.append(menuTree);
		accordionContent.append("</li>\n");
		
		boolean authority=false;
		Set<Role> menuRole=menu.getRole();
		for (Role role : roles) {
			for (Role m_role : menuRole) {
				if(m_role.getId()==role.getId())
					authority=true;
			}
		}
		if(authority){
			tree.append(accordionContent);
		}else if(menuTree.length()>20){
			tree.append(accordionContent);
		}
		
		return tree.toString();
	}

	public String getchildMenuTree(Menu menu, String rootUrl,Set<Role> roles) {
		
		StringBuffer tree = new StringBuffer();
		@SuppressWarnings("unchecked")
		Set<Menu> menus = menu.getMenu();
		if (menus.size() > 0) {
			tree.append("<ul>\n");
			for (Menu childMenu : menus) {
				StringBuffer childMenuTree = new StringBuffer();
				childMenuTree.append("<li>\n");
				if (childMenu.getType().equals("navTab")) {
					if (childMenu.getUrl() != null && !childMenu.getUrl().isEmpty()) {
						childMenuTree.append("<a href='" + rootUrl + childMenu.getUrl()
								+ "' target='navTab' rel='" + childMenu.getRel()
								+ "' title='" + childMenu.getTitle() + "' fresh='"
								+ childMenu.getFresh() + "' external='"
								+ childMenu.getExternal() + "' >"
								+ childMenu.getName() + "</a>\n");
					} else {					
						childMenuTree.append("<a href='javascript:;>" + childMenu.getName() + "</a>\n");
					}
				} else if (childMenu.getType().equals("dialog")) {
					if (childMenu.getUrl() != null && !childMenu.getUrl().isEmpty()) {
						childMenuTree.append("<a href='" + rootUrl + childMenu.getUrl()
								+ "' target='dialog' rel='" + childMenu.getRel()
								+ "' title='" + childMenu.getTitle()
								+ "' minable='" + childMenu.getMinable()
								+ "' mixable='" + childMenu.getMixable()
								+ "' resizable='" + childMenu.getResizable()
								+ "' drawable='" + childMenu.getDrawable()
								+ "' width='" + childMenu.getWidth() + "' height='"
								+ childMenu.getHeight() + "' fresh='"
								+ childMenu.getFresh() + "'>" + childMenu.getName()
								+ "</a>\n");
					} else {
						childMenuTree.append("<a href='javascript:;'>" + childMenu.getName() + "</a>\n");
					}
				}
				String menuTree=getchildMenuTree(childMenu, rootUrl,roles);
				childMenuTree.append(menuTree);
				childMenuTree.append("</li>\n");
				boolean authority=false;
				Set<Role> menuRole=childMenu.getRole();
				for (Role role : roles) {
					for (Role m_role : menuRole) {
						if(m_role.getId()==role.getId())
							authority=true;
					}
				}
				if(authority){
					tree.append(childMenuTree);
				}else if(menuTree.length()>20){
					tree.append(childMenuTree);
				}
			}
			tree.append("</ul>\n");
		}
		return tree.toString();
	}
}
